package com.novel.listen;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.novel.config.RedissonHelper;
import com.novel.entiy.Comment;
import com.novel.entiy.CommentSupport;
import com.novel.entiy.Novel;
import com.novel.entiy.event.CommentSupportEvent;
import com.novel.entiy.event.HotEvent;
import com.novel.mapper.CommentMapper;
import com.novel.mapper.CommentSupportMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.redisson.api.RLock;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * 评论点赞监听
 *
 * @author tanghao
 * @date 2022/4/18
 */
@Slf4j
@Component
public class CommentSupportListener {

    @Resource
    private RedissonHelper redissonHelper;

    @Resource
    private CommentMapper commentMapper;

    @Resource
    private CommentSupportMapper commentSupportMapper;

    /**
     * 监听点赞事件
     *
     * @param commentSupportEvent 评论点赞事件
     */
    @EventListener(CommentSupportEvent.class)
    public void onApplicationEvent(CommentSupportEvent commentSupportEvent) {
        RLock lock = redissonHelper.getLock("support-event-" + commentSupportEvent.getCommentId() + "-" +
                commentSupportEvent.getUserId());
        try {
            lock.lock(5, TimeUnit.SECONDS);
            Comment comment = commentMapper.selectById(commentSupportEvent.getCommentId());
            comment.setCommentNums(commentSupportEvent.getCommentSupportNum());
            commentMapper.updateById(comment);
            CommentSupport commentSupport = commentSupportMapper.selectOne(new QueryWrapper<CommentSupport>()
                    .eq(CommentSupport.COL_COMMENT_ID, commentSupportEvent.getCommentId())
                    .eq(CommentSupport.COL_USER_ID, commentSupportEvent.getUserId()));
            if (commentSupportEvent.getType().equals(0)) {
                if (ObjectUtils.isEmpty(commentSupport)) {
                    CommentSupport build = CommentSupport.builder().commentId(commentSupportEvent.getCommentId()).
                            userId(commentSupportEvent.getUserId())
                            .novelId(commentSupportEvent.getNovelId()).build();
                    commentSupportMapper.insert(build);
                }
            } else {
                commentSupportMapper.delete(new QueryWrapper<CommentSupport>().eq(CommentSupport.COL_COMMENT_ID,
                                commentSupportEvent.getCommentId())
                        .eq(CommentSupport.COL_USER_ID, commentSupportEvent.getUserId()));
            }
        } finally {
            lock.unlock();
        }
    }
}
